//
//  BYScrollImageView.m
//  DSA_Broker
//
//  Created by Bau-yin on 15/5/15.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "BYScrollImageView.h"
#import "UIImageView+AFNetworking.h"

@interface BYScrollImageView ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIPageControl *pageControl;

@property (nonatomic, strong) NSArray *imageURLArray;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) BOOL timerValid;

@end

@implementation BYScrollImageView

#pragma mark - View Life Cycle
- (id)initWithFrame:(CGRect)frame imageArray:(NSArray *)array
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = [UIColor whiteColor];
        self.userInteractionEnabled = YES;

        BOOL isEmptyArray = (array == nil || array.count <= 0);
        self.imageURLArray = isEmptyArray ? [self defaultImageArray] : [NSArray arrayWithArray:array];
        
        self.tableView = [self transformTableViewWithFrame:self.bounds];
        [self addSubview:self.tableView];

        self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 10, self.bounds.size.width, 6)];
        self.pageControl.backgroundColor = [UIColor clearColor];
        self.pageControl.pageIndicatorTintColor = [UIColor grayColor];
        self.pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
        self.pageControl.numberOfPages = array.count;
        self.pageControl.currentPage = 0;
        [self addSubview:self.pageControl];
        
        [self refresh:NO];
    }
    return self;
}

- (void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
    [self.tableView removeFromSuperview];
    self.tableView = nil;
    self.imageURLArray = nil;
}

#pragma mark - Methods
- (NSArray *)defaultImageArray
{
    NSMutableArray *array = [NSMutableArray array];
    [array addObject:@{@"photo_url":@"https://ss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=85eeab7546166d22382246d4201e3dc5/d043ad4bd11373f052174321a10f4bfbfbed0467.jpg"}];
    [array addObject:@{@"photo_url":@"http://g.hiphotos.baidu.com/image/pic/item/6f061d950a7b020815d1b8ff60d9f2d3572cc890.jpg"}];
    [array addObject:@{@"photo_url":@"http://www.c168c.com/images/attachement/jpg/site132/20110302/0016ecaae7b30ed8449e1c.jpg"}];
    return array;
}

- (UITableView *)transformTableViewWithFrame:(CGRect)frame
{
    CGRect tabelViewFrame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.height, frame.size.width);
    UITableView *tableView = [[UITableView alloc] initWithFrame:tabelViewFrame style:UITableViewStylePlain];
    tableView.center = CGPointMake(frame.origin.x + frame.size.width * 0.5, frame.origin.y + frame.size.height * 0.5);
    tableView.transform = CGAffineTransformMakeRotation(-M_PI / 2);
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.pagingEnabled = YES;
    return tableView;
}

- (void) refresh
{
    [self refresh:YES];
}

- (void) refresh:(BOOL)shouldReloadTable
{
    if (shouldReloadTable)
    {
        [self.tableView reloadData];
    }
    if (self.timer)  [self.timer invalidate];
    if (self.imageURLArray.count > 3)
    {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
        [self.tableView setContentOffset:CGPointMake(0, self.bounds.size.width) animated:YES];
    }
}

- (void) moveToIndex:(NSInteger)index
{
//    CGFloat rowHeight = (self.bounds.size.width-PADDING*2)/QFCarScrollMaxCount;
//    if (index > self.dataArr.count - QFCarScrollMaxCount) {
//        index = self.dataArr.count - QFCarScrollMaxCount;
//    }
//    [self.tableView setContentOffset:CGPointMake(0, rowHeight * index) animated:YES];
}

- (void)moveToBegin
{
    [self.tableView setContentOffset:CGPointMake(0, self.bounds.size.width) animated:NO];
}

#pragma mark - Timer
- (void)setTimerValid:(BOOL)timerValid
{
    if (self.timer)  [self.timer invalidate];
    
    if (timerValid && self.imageURLArray.count > 3)
    {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    }
}

- (void)timerAction:(NSTimer *)timer
{
    CGFloat width = self.bounds.size.width;
    NSInteger curIndex = self.tableView.contentOffset.y/width;
    [self.tableView setContentOffset:CGPointMake(0, width * ++curIndex) animated:YES];
    if (curIndex == self.imageURLArray.count - 1)
    {
        [self performSelector:@selector(moveToBegin) withObject:nil afterDelay:1];
        self.pageControl.currentPage = 0;
    }
    else
    {
        self.pageControl.currentPage ++;
    }
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.imageURLArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BYScrollImageViewCell"];
    for (UIView *view in cell.contentView.subviews)
    {
        [view removeFromSuperview];
    }
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BYScrollImageViewCell"];
    }
    cell.transform = CGAffineTransformMakeRotation(M_PI / 2);
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.userInteractionEnabled = YES;
    [imageView setImageWithURL:[NSURL URLWithString:([self.imageURLArray[indexPath.row] objectForKey:@"photo_url"])]];
    cell.backgroundView = imageView;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.bounds.size.width;
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[NSString stringWithFormat:@"%@",[self.imageURLArray[indexPath.row] objectForKey:@"link_adress"]] length] == 0)
    {
        return NO;
    }
    return YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (self.selectedBlock)
    {
        self.selectedBlock(self.imageURLArray[indexPath.row]);
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.timerValid = NO;
}

- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.timerValid = YES;
    if (self.imageURLArray.count > 3)
    {
        CGFloat width = self.bounds.size.width;
        NSInteger curIndex = scrollView.contentOffset.y / width;
        if (curIndex == 0)
        {
            [scrollView setContentOffset:CGPointMake(0, width * (self.imageURLArray.count - 2)) animated:NO];
        }
        
        if (curIndex == self.imageURLArray.count - 1)
        {
            [scrollView setContentOffset:CGPointMake(0, width) animated:NO];
        }
        self.pageControl.currentPage = scrollView.contentOffset.y/width - 1;
    }
}


@end
